package oneplay.YonghongBITools.utils;

import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class StandPrint {

    /**
     * 设置为标准打印格式，缩放到一页A4纸张，居中打印，
     *
     * @param xlsx         输入文件
     * @param landscape    是否横向
     * @param fitWidth     宽度缩放
     * @param fitHeight    高度缩放
     * @param outputStream 输出流
     */
    public static void write(byte[] xlsx, boolean landscape, Short fitWidth, Short fitHeight, OutputStream outputStream) throws IOException {
        try (Workbook workbook = new XSSFWorkbook(new ByteArrayInputStream(xlsx))) {
            workbook.forEach(sheet -> {
                sheet.setHorizontallyCenter(true); // 水平居中
                sheet.setVerticallyCenter(true); // 垂直居中
                PrintSetup ps = sheet.getPrintSetup();
                ps.setPaperSize(PrintSetup.A4_PAPERSIZE); // A4 纸张
                ps.setLandscape(landscape); // 是否横向
                sheet.setFitToPage(true); // 影响缩放单选按钮 false-缩放比例 true-调整为
                if (fitWidth != null) ps.setFitWidth(fitWidth);
                if (fitHeight != null) ps.setFitHeight(fitHeight);
            });
            workbook.write(outputStream);
            outputStream.flush();
        }
    }

}
